<template>
  <div>
    <div class="header">
      <span style="margin-left: 10px; text-align: right">关键字</span>
      <el-input
        placeholder="请输入关键字"
        v-model="req.keyword"
        style="width: 200px; margin-left: 10px"
      ></el-input>
      <span style="text-align: right; margin-left: 10px">开票日期</span>
      <el-date-picker
        v-model="req.dealDates"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions"
        style="margin-left: 10px"
      ></el-date-picker>
      <span style="text-align: right; margin-left: 10px">录入日期</span>
      <el-date-picker
        v-model="req.createDates"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions"
        style="margin-left: 10px"
      ></el-date-picker>

      <el-button
        plain
        type="primary"
        style="margin-left: 34px"
        icon="el-icon-search"
        @click="getMyInvoices()"
      >
        搜索
      </el-button>
      <el-button
        plain
        type="primary"
        style="margin-left: 10px"
        size="small"
        @click="outputExcel"
      >
        导出报表
      </el-button>
    </div>
    <div class="main">
      <el-tabs type="border-card" @tab-click="tabClick" style="height: 95%">
        <el-tab-pane
          style="height: 90%"
          :label="item.Description"
          v-for="item in statuses"
          :key="item.EnumValue"
        >
          <el-table
            style="overflow: auto"
            height="100%"
            :data="res.Items"
            stripe
            border
            highlight-current-row
          >
            <el-table-column type="index" width="40"></el-table-column>
            <el-table-column label="发票号码" width="120">
              <template slot-scope="scope">
                <el-popover
                  placement="top-start"
                  trigger="hover"
                  v-if="scope.row.IN_No"
                >
                  <div>[{{ scope.row.IN_ID }}]{{ scope.row.IN_No }}</div>
                  <p slot="reference">
                    {{
                      scope.row.IN_No.length > 10
                        ? scope.row.IN_No.substring(0, 10) + '...'
                        : scope.row.IN_No
                    }}
                  </p>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="发票金额" width="100">
              <template slot-scope="scope">{{ scope.row.IN_Fee }}元</template>
            </el-table-column>
            <el-table-column label="开票日期" width="160">
              <template slot-scope="scope">
                <el-tag
                  type="danger"
                  v-if="
                    scope.row.IN_DealDate < limitDate && status.EnumValue == 10
                  "
                >
                  逾期
                </el-tag>
                {{ scope.row.IN_DealDate | formatDate }}
              </template>
            </el-table-column>
            <el-table-column label="报销性质" width="80">
              <template slot-scope="scope">
                {{ scope.row.INTY_EnumTxt }}
              </template>
            </el-table-column>
            <el-table-column label="报销地址">
              <template slot-scope="scope">
                {{ scope.row.IN_AreaDesc }}
              </template>
            </el-table-column>
            <el-table-column
              label="报销案件"
              width="200"
              v-if="status.EnumValue == 100"
            >
              <template slot-scope="scope">
                <div
                  v-for="expCase in scope.row.ExpenseCases"
                  :key="expCase.CEX_ID"
                >
                  <el-link
                    slot="reference"
                    style="color: blue"
                    @click="toForm(expCase.CEX_FormID)"
                  >
                    {{ expCase.CS_No }}
                    <span v-if="expCase.FRS_Name">
                      [{{ expCase.FRS_Name }}]
                    </span>
                  </el-link>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="抬头" width="260">
              <template slot-scope="scope">
                {{ scope.row.IN_Title }}
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template slot-scope="scope">
                {{ scope.row.IN_Remark }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="160">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-picture"
                  @click="
                    curInvoice = scope.row
                    imageVis = true
                  "
                ></el-button>
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-edit"
                  @click="
                    curInvoice = scope.row
                    editInvoiceVis = true
                  "
                ></el-button>
                <el-button
                  v-if="scope.row.IN_Status == 10"
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                  @click="deleteInvoice(scope.row.IN_ID)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            layout="total,prev,pager,next,sizes"
            style="float: right"
            background
            :current-page.sync="req.pageIndex"
            :page-size="req.pageSize"
            :total="res.Total"
            :page-sizes="[12, 18]"
            @size-change="
              (val) => {
                req.pageSize = val
                getMyInvoices()
              }
            "
            @current-change="getMyInvoices()"
          ></el-pagination>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-drawer
      title="信息修改"
      :visible.sync="editInvoiceVis"
      :with-header="false"
      direction="rtl"
      size="480px"
    >
      <el-form
        v-if="curInvoice"
        label-width="100px"
        label-position="left"
        style="
          margin-left: 20px;
          margin-top: 20px;
          overflow: auto;
          height: 100vh;
        "
      >
        <el-form-item label="报销性质">
          <el-select
            filterable
            v-model="curInvoice.IN_Type"
            style="width: 300px"
          >
            <el-option
              v-for="(item, index) in invoiceTypes"
              :key="index"
              :label="item.INTY_EnumTxt"
              :value="item.INTY_ID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报销地址">
          <el-cascader
            style="width: 300px"
            :options="chinaAreaData"
            :value="areaConvert(curInvoice.IN_Area)"
            @change="areaChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="编号">
          <el-input v-model="curInvoice.IN_No" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="抬头">
          <el-input
            v-model="curInvoice.IN_Title"
            style="width: 300px"
          ></el-input>
        </el-form-item>

        <el-form-item label="价税合计">
          <el-input v-model="curInvoice.IN_Fee" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="税额">
          <el-input
            v-model="curInvoice.IN_TaxFee"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="金额">
          <el-input
            v-model="curInvoice.IN_FeeWithoutTax"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="开票日期">
          <el-date-picker
            align="right"
            v-model="curInvoice.IN_DealDate"
            placeholder="请选择开票日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="date"
            style="width: 300px"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="curInvoice.IN_Remark"
            style="width: 300px"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="warning" @click="editInvoice()">保存</el-button>
          <el-button type="text" @click="editInvoiceVis = false">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-image-viewer
      v-if="imageVis"
      :url-list="[fileURL + curInvoice.FL_SrcPath]"
      :on-close="closeImage"
    ></el-image-viewer>
  </div>
</template>
<script>
import elImageViewer from 'element-ui/packages/image/src/image-viewer'
import {
  getMyExpenseLimitDate,
  getInvoiceStatuses,
  getInvoiceTypes,
  getMyInvoices,
  editInvoice,
  deleteInvoice,
} from '@/api/core/invoice'
import {
  baseURL,
  fileRoot,
  fileUploadRoot,
  empIdName,
  tokenName,
} from '@/config'
import axios from 'axios'
import ticketIdentify from '@/views/web/case/components/ticketIdentify.vue'
import { provinceAndCityDataPlus, CodeToText } from 'element-china-area-data'
export default {
  components: { ticketIdentify, elImageViewer },
  data: function () {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            },
          },
        ],
      },
      req: {
        keyword: null,
        dealDates: [],
        createDates: [],
        pageIndex: 1,
        pageSize: 12,
        status: null,
      },
      res: {
        Items: [],
        Total: 0,
      },
      limitDate: null,
      curInvoice: null,
      status: null,
      statuses: [],
      invoiceTypes: [],

      chinaAreaData: provinceAndCityDataPlus,
      fileURL: baseURL + fileRoot,
      fileUploadUrl: baseURL + fileUploadRoot,
      uploadPercentage: 0,
      editInvoiceVis: false,

      ticketFile: null,
      imageVis: false,
    }
  },
  methods: {
    tabClick(val) {
      this.status = this.statuses.find((x) => x.Description == val.label)
      this.getMyInvoices()
    },
    toForm(formId) {
      this.$router.push({
        name: 'formInfoPage',
        query: { formId },
      })
    },
    closeImage() {
      this.imageVis = false
      return true
    },
    areaConvert(areas) {
      if (areas) return JSON.parse(areas)
    },
    areaChange(val) {
      this.curInvoice.IN_Area = JSON.stringify(val)
      this.curInvoice.IN_AreaDesc = ''
      val?.forEach((x) => {
        this.curInvoice.IN_AreaDesc += CodeToText[x]
      })
    },
    editInvoice() {
      editInvoice(this.curInvoice).then(() => {
        this.getMyInvoices()
        this.editInvoiceVis = false
      })
    },
    getMyExpenseLimitDate() {
      getMyExpenseLimitDate().then(({ data }) => {
        this.limitDate = data
      })
    },
    getInvoiceStatuses: function () {
      getInvoiceStatuses().then(({ data }) => {
        this.statuses = data
        this.status = this.statuses[0]
        this.getMyInvoices()
      })
    },
    getInvoiceTypes: function () {
      getInvoiceTypes().then(({ data }) => {
        this.invoiceTypes = data
      })
    },
    getMyInvoices: function () {
      this.req.status = this.status.EnumValue
      getMyInvoices(this.req).then(({ data }) => {
        this.res = data
      })
    },
    deleteInvoice(id) {
      this.$confirm(`是否删除该票据`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteInvoice(id).then(() => {
          this.getMyInvoices()
        })
      })
    },
    outputExcel() {
      if (
        !this.req.keyword &&
        this.req.createDates.length == 0 &&
        this.req.dealDates.length == 0
      ) {
        this.$message('请选择导出信息（关键字/开票日期/录入日期）')
        return
      }
      var config = {
        baseURL,
        headers: {},
        responseType: 'blob',
      }
      config.headers[tokenName] = this.$store.getters['user/accessToken']
      config.headers[empIdName] = this.$store.getters['user/curEmp'].EMP_ID
      this.req.status = this.status.EnumValue
      axios
        .post('/api/Case/Invoice/OutputMyInvoiceExcel', this.req, config)
        .then((response) => {
          var blob = new Blob([response.data])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = '差旅费报表.xls' //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch((error) => {
          console.log('response: ', error)
        })
    },
  },
  created: function () {
    var data = this.$store.getters['pagination/getRoutePage'](this.$route)
    Object.assign(this.$data, data)
    this.getInvoiceTypes()
    this.getMyExpenseLimitDate()
    this.getInvoiceStatuses()
  },
  beforeRouteLeave(to, from, next) {
    this.$store.dispatch('pagination/setRoutePage', {
      route: this.$route,
      pageData: this.$data,
    })
    next()
  },
}
</script>
<style scoped>
.header {
  width: 100%;
  padding-top: 10px;
  padding-bottom: 10px;
  height: auto;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  background: #ffffff;
  border-radius: 5px;
  border-bottom: #f4f8ff 2px solid;
  display: flex;
  margin-bottom: 11px;
  align-items: center;
}
.main {
  height: 95%;
}
</style>

<style>
.main .el-table .warning-row {
  background-color: oldlace;
}

.main .el-tabs__content {
  height: 90%;
}
</style>
